import { defineStore } from 'pinia'
import { login, logout, getUserInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'

export const useUserStore = defineStore('user', {
  state: () => ({
    token: getToken(),
    name: '',
    avatar: '',
    introduction: '',
    roles: []
  }),
  
  actions: {
    // 用户登录
    async login(userInfo) {
      try {
        const { username, password } = userInfo
        const response = await login({ name: username.trim(), password })
        const { data } = response
        this.token = data.authentication
        setToken(data.authentication)
        return Promise.resolve()
      } catch (error) {
        return Promise.reject(error)
      }
    },
    
    // 获取用户信息
    async getInfo() {
      try {
        const { data } = await getUserInfo(this.token)
        if (!data) {
          throw new Error('验证失败，请重新登录')
        }
        
        const { roles, name, avatar, introduction } = data
        
        // // 角色必须是非空数组
        // if (!roles || roles.length <= 0) {
        //   throw new Error('用户角色不能为空!')
        // }
        
        // this.roles = roles
        this.name = name
        this.avatar = avatar
        this.introduction = introduction
        return Promise.resolve(data)
      } catch (error) {
        return Promise.reject(error)
      }
    },
    
    // 用户登出
    async logout() {
      try {
        await logout(this.token)
        this.token = ''
        this.roles = []
        this.name = ''
        this.avatar = ''
        this.introduction = ''
        removeToken()
        resetRouter()
        // 重置路由加载状态
        window.hasRoutes = false
        return Promise.resolve()
      } catch (error) {
        return Promise.reject(error)
      }
    },
    
    // 重置Token
    resetToken() {
      this.token = ''
      this.roles = []
      this.name = ''
      this.avatar = ''
      this.introduction = ''
      removeToken()
      // 重置路由加载状态
      window.hasRoutes = false
    },
    
    // 更改角色
    async changeRoles(role) {
      // 模拟实际业务中原本很复杂的操作
      const token = role + '-token'
      
      this.token = token
      setToken(token)
      
      const { roles } = await this.getInfo()
      
      resetRouter()
      
      const permissionStore = usePermissionStore()
      const accessRoutes = await permissionStore.generateRoutes(roles)
      
      // 动态添加可访问路由
      accessRoutes.forEach(route => {
        router.addRoute(route)
      })
    }
  }
}) 